<?php

namespace Coldwind;

/**
 * @author ZXZ <zxz054321@163.com>
 */
class Pagination {

    public $listRows; // 列表每页显示行数
    public $totalRows; // 总行数
    public $rollPage = 11; // 分页栏每页显示的页数
    public $lastSuffix = true; // 最后一页是否显示总页数

    /**
     * 架构函数
     * @param array $totalRows  总的记录数
     * @param array $listRows  每页显示记录数
     * @param array $parameter  分页跳转的参数
     */

    public function __construct($totalRows, $listRows) {
        /* 基础设置 */
        $this->totalRows = $totalRows; //设置总记录数
        $this->listRows = $listRows;  //设置每页显示行数
    }

    /**
     * 总页数
     * @return type
     */
    public function getPageCount() {
        return ceil($this->totalRows / $this->listRows);
    }

    public function getPagination($pageIndex = 1) {
        if (0 == $this->totalRows)
            return NULL;

        $pagination = array();

        /* 计算分页信息 */
        $totalPages = $this->getPageCount();
        if ($totalPages < 2)
            return NULL;
        $pagination['total'] = $totalPages;

        if (!empty($totalPages) && $pageIndex > $totalPages) {
            $pageIndex = $totalPages;
        }

        /* 计算分页零时变量 */
        $now_cool_page = $this->rollPage / 2;
        $now_cool_page_ceil = ceil($now_cool_page);

        $pageArray = array();

        //上一页
        $up_row = $pageIndex - 1;
        if ($up_row > 0) {
            $pagination['prev'] = $up_row;
        }

        //下一页
        $down_row = $pageIndex + 1;
        if ($down_row <= $totalPages) {
            $pagination['next'] = $down_row;
        }

        //第一页
        if ($totalPages > $this->rollPage && ($pageIndex - $now_cool_page) >= 1) {
            $pagination['first'] = 1;
        }

        //最后一页
        if ($totalPages > $this->rollPage && ($pageIndex + $now_cool_page) < $totalPages) {
            $pagination['last'] = $totalPages;
        }

        //数字连接
        $link_page = array();
        for ($i = 1; $i <= $this->rollPage; $i++) {
            if (($pageIndex - $now_cool_page) <= 0) {
                $page = $i;
            } elseif (($pageIndex + $now_cool_page - 1) >= $totalPages) {
                $page = $totalPages - $this->rollPage + $i;
            } else {
                $page = $pageIndex - $now_cool_page_ceil + $i;
            }
            if ($page > 0 && $page != $pageIndex) {
                if ($page <= $totalPages) {
                    $link_page[] = $page;
                } else {
                    break;
                }
            } else {
                if ($page > 0 && $totalPages != 1) {
                    $link_page[] = -1;
                    $pagination['current'] = $page;
                }
            }
        }
        $pagination['link'] = $link_page;

        return $pagination;
    }

}
